package com.keshan.service.impl;

import com.keshan.mapper.MdUserMapper;
import com.keshan.pojo.MdUser;
import com.keshan.pojo.MdUserExample;
import com.keshan.service.MdUserServices;
import com.keshan.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author keshan
 * @date 2022/10/18 - 10:00
 */

@Service
public class MdUserServicesImpl implements MdUserServices {

    //注入mapper
    @Autowired
    MdUserMapper mdUserMapper;


    @Override
    public int insertBySelectiveMdUser(MdUser mdUser) {
        return mdUserMapper.insertSelective(mdUser);
    }

    @Override
    public List<MdUser> getMdUserListByMduser(MdUser mdUser) {
        MdUserExample mdUserExample = new MdUserExample();
        MdUserExample.Criteria criteria = mdUserExample.createCriteria();
        criteria.andUsernameEqualTo(mdUser.getUsername());
        criteria.andPasswordEqualTo(mdUser.getPassword());
        return mdUserMapper.selectByExample(mdUserExample);
    }

    @Override
    public int updateMdUserByPrimaryKeySelective(MdUser mdUser) {
        return mdUserMapper.updateByPrimaryKeySelective(mdUser);
    }

    @Override
    public int updateMdUserByUserName(MdUser mdUser) {
        return mdUserMapper.updateByUserName(mdUser);
    }


    @Override
    public int gerIdByUserName(String Username) {
        return mdUserMapper.getIdByUserName(Username);
    }

    /**
     * @param openid 微信openid
     * @return nick_name&jwt的token
     * @author tangzheng
     * @date 2023/2/11 21:37
     * @description 根据openid登录, 若第一次登录则注册
     */
    @Override
    public Map<String, String> doWxLogin(String openid) {
        MdUser user = mdUserMapper.selectUserByOpenid(openid);
        String username = user.getUsername();
        if (StringUtils.isEmpty(username)) {
            username = UUID.randomUUID().toString().replace("-", "");
            MdUser mdUser = new MdUser();
            mdUser.setUsername(username);
            mdUser.setOpenid(openid);
            mdUserMapper.insertSelective(mdUser);
        }
        Map<String, String> map = new HashMap<>();
        map.put("username", username);
        String token = JWTUtils.getToken(map);
        map.put("nickName", user.getNickName());
        map.put("token", token);
        return map;
    }

    /**
     * @param user 需要更改的信息
     * @author tangzheng
     * @date 2023/2/11 22:52
     * @description 根据用户名更改用户相关信息
     */
    @Override
    public void updateByUsernameSelective(MdUser user) {
        mdUserMapper.updateByUsernameSelective(user);
    }
}
